﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Dynamic;

namespace DannyFramework.Results
{
    /// <summary>
    /// 通用异常过滤器
    /// </summary>
    public class CommonExceptionFilter : IExceptionFilter,IOrderedFilter
    {
        public int Order => int.MinValue;  //设置优先级；最小为最高优先级； 代替 ABPvNext 默认的 ExceptionFilter

        /// <summary>
        /// 拦截异常，返回统一包装
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            if (context.Exception is CommonException commonException)
            {
                //根据CommonException定制包装
                CommonException commonResult = new CommonException();
                commonResult.Code = commonException.Code;
                commonResult.Message = commonException.Message;
                commonResult.ErrorInfo = context.Exception.Message;

                context.Result = new JsonResult(commonResult);
            }
            else
            {
                //统一包装
                CommonException commonResult = new CommonException();
                commonResult.Code = 1;
                commonResult.Message = "操作失败";
                commonResult.ErrorInfo = context.Exception.Message;

                context.Result = new JsonResult(commonResult);
            }
            //标记异常结果已经返回
            context.ExceptionHandled= true;
        }
    }
}
